﻿using IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Models.MiniuiModes;
using Models.UserModels;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
using ViewModels;

namespace MiunUI.Home.Controllers
{
    [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        public readonly IUserService _userService;
        public readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ILogger<HomeController> _logger;
        public HomeController(IUserService userService, 
            IWebHostEnvironment webHostEnvironment,
            ILogger<HomeController> logger
            )
        {
            _userService = userService;
            _webHostEnvironment = webHostEnvironment;
            _logger = logger;
        }
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult UserList() // 用户视图
        {
            return View();
        }
        public IActionResult UserDataList(UserModel userModel) // 查询用户信息
        {
            var List = _userService.GetUserList(userModel);
            return Ok(List);
        }
        public IActionResult CreateUserList()
        {
            return View();
        }
        [HttpPost]
        public IActionResult ActionUserList(UserViewModel userViewModel)
        {
            if (userViewModel.USERID == 0)
            {
                return Ok(_userService.CreateUserList(userViewModel));
            }
            else
            {
                return Ok(_userService.UpdateUserList(userViewModel));

            }
        }
        public IActionResult GetUserDetails(int id)
        {
            var Items = _userService.GetUserDetails(id);
            return Ok(Items);
        }
        [HttpPost]
        public IActionResult GetPHoto(IFormFile File)
        {
            string filePath = string.Empty;
            if (File != null)
            {
                string uploadsFplder = Path.Combine(_webHostEnvironment.WebRootPath, "images");
                string FileName = Guid.NewGuid().ToString() + "_" + File.FileName;
                filePath = Path.Combine(uploadsFplder, FileName);
                File.CopyTo(new FileStream(filePath, FileMode.Create));
            }
            //ImagesModel imagesModel = new ImagesModel()
            //{
            //    USERID = USERID,
            //    IMAGENAME = filePath,
            //    IMAGETYPE = File.ContentType,
            //};
            return Ok(filePath);
        }
        public IActionResult DeleteUserList(int USERID)
        {
            return Ok(_userService.DeleteUserList(USERID));
        }
        public ActionResult Print_Excel(int USERID)
        {
            string uploadsFplder = Path.Combine(_webHostEnvironment.WebRootPath, "Updateload");//存放路径
            string FileName = Guid.NewGuid().ToString("N"); //重命名
            string filePath = Path.Combine(uploadsFplder, FileName)+ ".xlsx"; // 拼接路径
            string LocalFilePath = uploadsFplder + "\\员工信息表.xlsx";//模版文件地址
            try
            {
                var Items = _userService.GetUserDetails(USERID); // 获取打印数据
                #region 填充数据
                //根据路径找到文件并打开
                using (FileStream file = new FileStream(LocalFilePath, FileMode.Open, FileAccess.Read))
                {
                    XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
                    XSSFSheet sheet = (XSSFSheet)xssfworkbook.GetSheet(".1");//读取数据
                    #region 表格数据
                    string sex = Items.USERSEX == 1 ? "男" : "女";
                    sheet.GetRow(1).GetCell(1).SetCellValue(Items.USERNAME.ToString());//姓名，获取第2行第2列
                    sheet.GetRow(1).GetCell(4).SetCellValue(sex);//性别，获取第2行第5列
                    sheet.GetRow(1).GetCell(6).SetCellValue(Items.USERBRITH.ToString());//出生日期，获取第2行第7列
                    sheet.GetRow(2).GetCell(1).SetCellValue(Items.USERAGE.ToString());//年龄，获取第3行第2列
                    sheet.GetRow(2).GetCell(4).SetCellValue(Items.USERCARD.ToString());//身份证，获取第3行第5列
                    sheet.GetRow(4).GetCell(1).SetCellValue(Items.PROVINCE.ToString());//省，获取第5行第2列
                    sheet.GetRow(4).GetCell(6).SetCellValue(Items.CITY.ToString());//市，获取第5行第7列
                    sheet.GetRow(5).GetCell(1).SetCellValue(Items.COUNTY.ToString());//区，获取第6行第2列
                    sheet.GetRow(7).GetCell(2).SetCellValue(Items.USERPHONE.ToString());//联系电话，获取第8行第3列
                    #endregion
                    
                    #region 图片数据
                    if (Items.USERPHOTO != null)
                    {
                     byte[] bytes = System.IO.File.ReadAllBytes(Items.USERPHOTO.ToString()); //打开一个二进制文件，将文件的内容读入一个字节数组，然后关闭 文件。
                    int pictureIdx = xssfworkbook.AddPicture(bytes, PictureType.JPEG); // 
                    XSSFSheet tushi = (XSSFSheet)xssfworkbook.GetSheet(".1");
                    IDrawing patriarch = tushi.CreateDrawingPatriarch();
                    //插图片的位置
                    XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 8, 1, 10, 8);
                    //把图片插到相应的位置
                    XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                        //pict.Resize();
                    }
                    #endregion
                    FileStream fs = System.IO.File.OpenWrite(filePath);//创建打印表格
                    xssfworkbook.Write(fs);//打开写入数据
                    fs.Close();//关闭释放资源
                }
                #endregion
                var result = new AjaxMsgModel
                {
                    BackUrl = "/Updateload/" + FileName + ".xlsx",//文件地址
                    Data = "员工信息表.xlsx",//文件名称
                    Msg = "打印成功！",
                    Statu = 1
                };
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
                return Json(new AjaxMsgModel() { Msg = $"打印失败,{ex.Message}", Statu = 2 });
            }
        }
        // 菜单列表视图
        public IActionResult MenuListIndex()
        {
            return View();
        }
        public IActionResult GetMenuList()
        {
            return Ok(_userService.GetMenuList());
        } // 左侧菜单
        public IActionResult GetUserMenuList(int ROLEID) // 菜单表格树形数据
        {
            return Json(_userService.GetUserMenuList(ROLEID));
        }
        public IActionResult UserRole() // 用户角色
        {
            return View();
        }
        public IActionResult GetUSERROLEList() // 获取用户角色列表数据
        {
            return Ok(_userService.GetUSERROLEList());
        }
    }
}
